import {
	apiLoginUrl,
	apiCodeChangUser,
	apiSetUserName,
	apiLogout,
	apiGetUserInfoByToken,
} from '@/api/user.js'
var mixins = {
	data() {
		return {
			companyUserInfo: {}
		}
	},
	methods: {
		// 登录
		login(callback) {
			// #ifdef H5
			// 微信公众号授权方式和成功回调
			this.loginWeixinH5('snsapi_userinfo', callback)
			// #endif
		},
		// 登出后清除所有数据
		logout() {
			return new Promise((resolve, reject) => {
				uni.removeStorageSync('company_token')
				uni.removeStorageSync('companyUserInfo')
				uni.removeStorageSync('cid')
				resolve()
			});
		},
		//微信H5登录
		async loginWeixinH5(scope, callback) {

			// 微信H5环境
			/**
			 * 清除浏览器原始数据
			 * 判断token是否存在,是否授权,如果存在token,直接走回调函数
			 * 获取微信提供的code失败,表示未oauth2跳转授权,跳转oauth2去授权
			 * 获取微信提供的code成功,向后端发送code,获取用户信息,然后再走回调
			 */
			// 清除浏览器原始数据
			//uni.removeStorageSync('companyUserInfo')
			let company_token = uni.getStorageSync('company_token')
			// 判断company_token是否存在
			if (company_token) {
				// 存在token,直接走回调函数
				await this.getUserinfo(true)
				typeof callback == 'function' && callback(null)
			} else {
				// 页面获取code
				let code = this.$fn.getUrlVal('code')
				if (!code) {
					// 获取code失败,表示未oauth2跳转授权,跳转oauth2去授权
					// 发送请求,并传递当前页面,跳转到授权页获取code后,返回传递的页面上
					apiLoginUrl({
						redirect_url: uni.getStorageSync('initUrl')
					}).then((res) => {
						location.href = res.url
					})
				} else {
					//获取code成功,向后端发送code,获取用户信息
					let res = await apiCodeChangUser({
						code
					})
					res.token && uni.setStorageSync('company_token', res.token)
					// await this.setUserName(res)
					await this.getUserinfo(true)
					typeof callback == 'function' && callback(null)
				}
			}
		},
		//改名字
		setUserName(res) {
			return new Promise((resolve, reject) => {
				if (res.user_id == res.name) {
					uni.showModal({
						title: '修改昵称',
						content: '',
						showCancel: false,
						editable: true,
						success: async (showModalRes) => {
							if (showModalRes.confirm) {
								console.log('用户点击确定');
								if (showModalRes.content) {
									await apiSetUserName({
										name: showModalRes.content
									})
								}
								resolve()
							}
						}
					});
					return
				}
				resolve()
			})
		},

		// 必须使用微信H5
		needWeixinH5() {
			// #ifdef H5
			return new Promise((resolve, reject) => {
				if (!this.$fn.isWeiXin()) {
					// 非微信环境下,请使用微信浏览器
					document.documentElement.innerText = '请用使用微信浏览器'
					document.documentElement.style.textAlign = 'center'
					document.documentElement.style.paddingTop = '100px'
					document.documentElement.style.margin = 'auto'
					reject()
				}
				resolve()
			});
			// #endif
		},
		//初始化地址,用户保存初始化过来的联系内传参信息
		async initUrl(opts) {
			return new Promise((resolve, reject) => {
				// #ifdef H5
				uni.setStorageSync('initUrl', window.location.href);
				// #endif
				resolve()
			});
		},
		// 调试使用,设置token,避免授权问题
		async isDebugging() {
			// #ifdef H5
			if (process.env.NODE_ENV === 'development') {
				return new Promise((resolve, reject) => {
					let company_token = this.$config.token
					uni.setStorageSync('company_token', company_token)
					resolve()
				});
			}
			// #endif
		},
		// 获取用户信息
		async getUserinfo(isloading = false) {
			if (isloading) {
				let res = await apiGetUserInfoByToken()
				await this.setUserName(res.data)
				this.companyUserInfo = res.data
				uni.setStorageSync('companyUserInfo', res.data)
				if (!res.data?.store_name) {
					uni.showModal({
						title: '提示',
						content: '检测到您还没有绑定门店,请您联系后台管理员为您绑定门店后,再刷新尝试进入',
						showCancel: false,
						confirmText: '好的',
						confirmColor: '#00A191',
					});
				}
				return res.data
			} else {
				return uni.getStorageSync('companyUserInfo') || null
			}
		},
		// 自己拼接授权地址,接收传参的授权方式
		setOauthUrl(scope) {
			let data = {
				appid: ``,
				redirect_uri: uni.getStorageSync('initUrl'),
				response_type: 'code',
				scope: '',
				state: ''
			}
			let add_uri = this.$fn.objToUrl(data)
			//`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${你的appid}&redirect_uri=${授权后重定向地址}&response_type=code&scope=${授权的方式静默/弹窗}#wechat_redirect`
			const wx_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?' + add_uri + '#wechat_redirect'
			location.href = wx_url
		},
		// 微信支付
		wechatPay(payment) {
			// #ifdef MP-WEIXIN
			return new Promise((resolve, reject) => {
				uni.requestPayment({
					provider: 'wxpay',
					timeStamp: payment.timeStamp || String(Date.now()),
					nonceStr: payment.nonceStr || '',
					package: payment.package || '',
					signType: payment.signType || '',
					paySign: payment.paySign || '',
					success: function(res) {
						resolve(res);
					},
					fail: function(err) {
						uni.showToast({
							title: '支付失败',
							icon: 'none'
						})
						reject(err);
					}
				});
			})
			// #endif
			// 微信H5支付
			// #ifdef H5
			return new Promise((resolve, reject) => {
				WeixinJSBridge.invoke('getBrandWCPayRequest', {
					appId: payment.appId,
					timeStamp: payment.timestamp,
					nonceStr: payment.nonceStr,
					package: payment.package,
					signType: 'MD5',
					paySign: payment.paySign
				}, function(res) {
					if (res.err_msg == 'get_brand_wcpay_request:ok') {
						resolve(res);
					} else if (res.err_msg == 'get_brand_wcpay_request:cancel') {
						uni.showToast({
							title: '支付失败',
							icon: 'none'
						})
						reject(res);
					}
				})
			})
			// #endif
		},
		// 拨打电话
		makeCallFn(data) {
			console.log('makeCallFn')
			window.location.href = `tel:${10086}`
		},
		// 发起聊天
		sendChatFn(data) {
			console.log('sendChatFn', )
		},
	}
}
export default mixins